<template>
  <div ref="echartsRef" class="echarts-container"></div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, nextTick, watch, ref } from 'vue';
import * as echarts from 'echarts';
import type { ECharts, EChartsOption } from 'echarts';

interface EchartsDataItem {
  name: string;
  value: number;
  itemStyle: {
    color: string;
  };
  clickData?: any;
}

interface Props {
  title: string;
  echartsData: EchartsDataItem[] | undefined;
  value: number;
}

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  echartsData: {
    type: Array as PropType<EchartsDataItem[]>,
    default: () => []
  },
  value: {
    type: Number,
    default: 0
  }
});
const emit = defineEmits<{
  (e: 'clickData', params: any): void;
}>();

const echartsRef = ref<HTMLElement | null>(null);
const chartInstance = ref<ECharts | null>(null);

// 初始化图表
const initChart = () => {
  if (!echartsRef.value) return;

  // 如果已有实例则先销毁
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }

  chartInstance.value = echarts.init(echartsRef.value);
  updateChart();
};

// 更新图表
const updateChart = () => {
  if (!chartInstance.value || !props.echartsData?.length) return;

  const { colors, seriesData, sum } = processChartData(props.echartsData);
  const options = getChartOptions(colors, seriesData, sum);

  chartInstance.value.setOption(options);
  setupChartEvents();
};

// 处理图表数据
const processChartData = (data: EchartsDataItem[]) => {
  const colors: string[] = [];
  const seriesData: Array<{ name: string; value: number }> = [];
  let sum = 0;

  data.forEach((item) => {
    colors.push(item.itemStyle.color);
    seriesData.push({ name: item.name, value: item.value });
    sum += Number(item.value);
  });

  return { colors, seriesData, sum };
};

// 获取图表配置
const getChartOptions = (
  colors: string[],
  seriesData: Array<{
    name: string;
    value: number;
  }>,
  sum: number
): EChartsOption => ({
  color: colors,
  title: {
    show: true,
    text: '报警总数',
    subtext: String(props.value || 0),
    left: 'center',
    top: '42%',
    textStyle: {
      color: '#fff',
      fontSize: 14,
      fontWeight: 400
    },
    subtextStyle: {
      color: '#00FFFF',
      fontSize: 12,
      fontWeight: 700,
      fontFamily: 'PangMenZhengDao'
    }
  },
  tooltip: {
    position: [50, 50],
    formatter: (params: any) => {
      const percentage = sum !== 0 ? (Number(params.value) / sum) * 100 : 0;
      return `
        ${params.seriesName}<br/>
        <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>
        ${params.name}占比:${percentage.toFixed(2)}%<br/>
      `;
    }
  },
  legend: {
    orient: 'horizontal',
    left: 'center',
    bottom: '0',
    itemGap: 10,
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      color: '#fff',
      fontSize: 13
    }
  },
  series: [
    {
      name: props.title,
      type: 'pie',
      radius: ['50%', '70%'],
      center: ['50%', '50%'],
      label: {
        show: false,
        formatter: '{c}',
        fontSize: 13
      },
      data: seriesData
    }
  ]
});

// 设置图表事件
const setupChartEvents = () => {
  if (!chartInstance.value) return;

  chartInstance.value.off('click');
  chartInstance.value.on('click', (params: any) => {
    emit('clickData', params);
  });
};

// 处理窗口大小变化
const handleResize = () => {
  chartInstance.value?.resize();
};

// 初始化
onMounted(() => {
  nextTick(() => {
    initChart();
    // 使用setTimeout确保DOM完全渲染
    setTimeout(() => {
      handleResize();
    }, 100);
  });

  window.addEventListener('resize', handleResize);
});

// 清理
onBeforeUnmount(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
    chartInstance.value = null;
  }
  window.removeEventListener('resize', handleResize);
});

// 监听数据变化
watch(
  () => [props.echartsData, props.value],
  () => {
    updateChart();
  },
  { deep: true }
);
</script>

<style scoped>
.echarts-container {
  width: 100%;
  height: 100%;
}
</style>
